/*
 * 标签组件 - Tag Component
 * 显示热门标签列表
 */
import { TagEntity } from '@/models/tag';
import { getTagList } from '@/services/Tag/api';
import { TagsOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { Card, message, Tag, Tooltip } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

interface TagComponentProps {
  className?: string;
}

const TagComponent: React.FC<TagComponentProps> = ({ className }) => {
  const [tagList, setTagList] = useState<TagEntity[]>([]);
  const [tagLoading, setTagLoading] = useState(false);

  useEffect(() => {
    const fetchTagList = async () => {
      setTagLoading(true);
      try {
        const tagsResponse = await getTagList();

        // 使用优化后的API响应处理
        if (tagsResponse.success && tagsResponse.data) {
          setTagList(tagsResponse.data);
        } else {
          message.error('获取标签列表失败');
        }
      } catch (error) {
        console.error('获取标签列表错误:', error);
        message.error('获取标签列表失败，请稍后重试');
      } finally {
        setTagLoading(false);
      }
    };

    fetchTagList();
  }, []);

  // 处理标签点击事件
  const handleTagClick = (tag: TagEntity) => {
    history.push(`/tag/${tag.id}`);
  };

  return (
    <Card
      className={`${styles.card} ${styles.tagCard} ${className || ''}`}
      title={
        <div className={styles.cardTitle}>
          <TagsOutlined className={styles.titleIcon} />
          <span>热门标签</span>
        </div>
      }
      loading={tagLoading}
    >
      <div className={styles.tagsContainer}>
        {tagList.map((tag) => (
          <Tooltip key={tag.id} title={`查看「${tag.tagName}」相关文章`}>
            <Tag
              color={tag.color}
              className={styles.tagItem}
              onClick={() => handleTagClick(tag)}
            >
              {tag.tagName}
            </Tag>
          </Tooltip>
        ))}
        {tagList.length === 0 && !tagLoading && (
          <div className={styles.emptyState}>
            <TagsOutlined className={styles.emptyIcon} />
            <span>暂无标签</span>
          </div>
        )}
      </div>
    </Card>
  );
};

export default TagComponent;
